package com.zx.flow.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zx.flow.api.execute.request.query.UserQueryForm;
import com.zx.flow.api.execute.response.Response;
import com.zx.flow.api.util.JWTUtil;
import com.zx.flow.db.dao.FlowConfigDao;
import com.zx.flow.db.entity.FlowConfigEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.io.File;
import java.util.List;
import org.jacoco.ant.DumpTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 统一封装结果
 */
@RestController
@RequestMapping("/test")
@Tag(name = "测试")
public class ResponseTestController {

    @RequestMapping("/token")
    @Operation(summary = "获得测试token")
    public String getToken() {
        return JWTUtil.generateToken("test-key", "test-value", "test-key");
    }

    @PostMapping("dump")
    public Response<Boolean> dumpCoverageFile() {
        DumpTask dumpTask = new DumpTask();
        // dump文件地址
        dumpTask.setDestfile(new File("D://coverage/code-cover.exec"));
        // 多次dump追加形式
        dumpTask.setAppend(true);
        // 选一个空闲接口即可
        dumpTask.setPort(8888);
        // 默认本机
        dumpTask.setAddress("127.0.0.1");
        dumpTask.execute();
        return Response.success(true);
    }

    /**
     * http://127.0.0.1:8888/response/advice/test1?name=tom
     * 默认的返回格式
     * {
     * "status": 5000,
     * "msg": "Validation failed for argument [0] in public com.zx.flow.api.execute.response.Response
     * com.zx.flow.controller.ResponseAdviceController.test1(com.zx.flow.request.UserQueryForm): [Field error in object
     * 'userQueryForm' on field 'name': rejected value []; codes [NotEmpty.userQueryForm.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty];
     * arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userQueryForm.name,name];
     * arguments []; default message [name]]; default message [参数不能为空]] ",
     * "data": null
     * }
     *
     * @param form
     * @return
     */
    @PostMapping(value = "/test1")
    public Response test1(@Valid @RequestBody UserQueryForm form) {
        try {
            return Response.success(form.getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 优化返回格式
     *
     * {
     * "status": 5000,
     * "msg": "test2.form.name: 参数不能为空",
     * "data": null
     * }
     *
     * @param form
     * @param bindingResult
     * @return
     */
    @PostMapping(value = "/test2")
    public Response test2(@Valid @RequestBody UserQueryForm form, BindingResult bindingResult) {
        try {
            if (form.valid(bindingResult)) {
                return Response.success(form.getName());
            }
            return Response.fail(form);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/test3")
    public Response<Boolean> test3(@NotBlank(message = "用户ID不能为空") String userId) {
        return Response.success(true);
    }


    @Autowired
    private FlowConfigDao flowConfigDao;

    @RequestMapping("/all")
    public List<FlowConfigEntity> get() {
        return flowConfigDao.selectList(Wrappers.lambdaQuery());
    }

    @RequestMapping("/save1")
    @Transactional
    public String save1() {
        FlowConfigEntity entity = new FlowConfigEntity();
        entity.setId("");
        entity.setFlowCode("");
        entity.setFlowName("");
        entity.setEnable(false);
        entity.setVersion(0);
        entity.setConfig("");

        this.flowConfigDao.insert(entity);

        return "ok";
    }

    @RequestMapping("/save2")
    @Transactional(rollbackFor = Exception.class)
    public String save2() {
        FlowConfigEntity entity = new FlowConfigEntity();
        entity.setId("");
        entity.setFlowCode("");
        entity.setFlowName("");
        entity.setEnable(false);
        entity.setVersion(0);
        entity.setConfig("");

        this.flowConfigDao.insert(entity);
        if (1 == 1) {
            throw new RuntimeException("123");
        }
        entity.setId(null);
        this.flowConfigDao.insert(entity);

        return "ok";
    }

}
